<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>向量检索</title>
    <!-- Element UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="../css/style.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- API请求管理 -->
    <script src="../js/api.js"></script>
    <script>
        // 使用父窗口的全局变量
        const API_BASE_URL = window.parent.appGlobal.API_BASE_URL || '/api';
    </script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",Arial,sans-serif;
        }
        .component-container {
            padding: 15px;
        }
        .component-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .search-form {
            margin-bottom: 20px;
        }
        
        .search-results h4 {
            margin-bottom: 15px;
            color: #606266;
        }
        
        .search-result-card {
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .search-result-card:hover {
            transform: translateY(-2px);
        }
        
        .search-result-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .result-id {
            color: #409EFF;
        }
        
        .result-score {
            color: #67C23A;
            font-weight: bold;
        }
        
        .search-result-content {
            color: #606266;
            white-space: pre-line;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 0;
            color: #909399;
        }
        .empty-state i {
            font-size: 50px;
            margin-bottom: 10px;
        }
        .empty-state small {
            display: block;
            margin-top: 10px;
            color: #C0C4CC;
        }
        .document-content {
            white-space: pre-wrap;
            padding: 10px;
            background-color: #f5f7fa;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="component-container">
            <div class="component-header">
                <h3>向量检索{{ activeCollection ? ' - ' + activeCollection.name : '' }}</h3>
                <div>
                    <el-select 
                        v-model="selectedCollection" 
                        placeholder="切换集合" 
                        size="small" 
                        @change="switchCollection"
                        style="margin-right: 10px;">
                        <el-option
                            v-for="item in collections"
                            :key="item.name"
                            :label="item.name"
                            :value="item.name">
                            <span style="float: left">{{ item.name }}</span>
                            <span style="float: right; font-size: 12px; color: #8492a6; margin-right: 20px">
                                {{ item.document_count || 0 }}篇文档
                            </span>
                        </el-option>
                    </el-select>
                    <el-button 
                        type="text" 
                        icon="el-icon-setting" 
                        @click="openSettings">
                        搜索设置
                    </el-button>
                </div>
            </div>
            
            <div v-if="!isActiveCollectionValid" class="empty-state">
                <i class="el-icon-folder"></i>
                <p>请先选择一个集合</p>
            </div>
            
            <template v-else>
                <!-- 搜索表单 -->
                <div class="search-form">
                    <el-input
                        v-model="searchQuery"
                        placeholder="输入搜索内容..."
                        :disabled="loading"
                        @keyup.enter.native="search"
                        clearable>
                        <el-button 
                            slot="append" 
                            icon="el-icon-search" 
                            @click="search" 
                            :loading="loading">
                            搜索
                        </el-button>
                    </el-input>
                </div>
                
                <!-- 搜索结果 -->
                <div v-if="searchResults.length > 0" class="search-results">
                    <h4>搜索结果 ({{ searchResults.length }})</h4>
                    
                    <el-card 
                        v-for="(result, index) in searchResults" 
                        :key="index"
                        class="search-result-card"
                        shadow="hover"
                        @click.native="viewDocument(result.document)">
                        <div class="search-result-header">
                            <span class="result-id">ID: {{ result.document.id }}</span>
                            <span class="result-score">相似度: {{ (result.score * 100).toFixed(2) }}%</span>
                        </div>
                        <div class="search-result-content">
                            {{ formatContent(result.document.content) }}
                        </div>
                    </el-card>
                </div>
                
                <!-- 无结果状态 -->
                <div v-else-if="searchQuery && !loading" class="empty-state">
                    <i class="el-icon-search"></i>
                    <p>没有找到匹配的结果</p>
                </div>
                
                <!-- 默认状态 -->
                <div v-else-if="!loading" class="empty-state">
                    <i class="el-icon-search"></i>
                    <p>输入关键词进行向量语义搜索</p>
                    <small>向量搜索可以找到语义相似的内容，而非仅限于关键词匹配</small>
                </div>
            </template>
            
            <!-- 搜索设置对话框 -->
            <el-dialog title="搜索设置" :visible.sync="settingsDialogVisible" width="30%">
                <el-form label-width="140px">
                    <el-form-item label="最大结果数量">
                        <el-input-number 
                            v-model="settings.limit" 
                            :min="1" 
                            :max="100"
                            controls-position="right">
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="最低相似度阈值">
                        <el-slider 
                            v-model="settings.minScore" 
                            :min="0" 
                            :max="1" 
                            :step="0.05"
                            show-input>
                        </el-slider>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    searchQuery: '',
                    searchResults: [],
                    loading: false,
                    settings: {
                        limit: 10,
                        minScore: 0.5
                    },
                    settingsDialogVisible: false,
                    selectedCollection: '',
                    collections: window.parent.appGlobal.collections || []
                };
            },
            computed: {
                // 从全局变量获取活动集合
                activeCollection() {
                    return window.parent.appGlobal.activeCollection;
                },
                isActiveCollectionValid() {
                    const collection = this.activeCollection;
                    return collection && collection.name;
                }
            },
            watch: {
                // 监听活动集合变化
                activeCollection: {
                    handler(newVal, oldVal) {
                        if ((!oldVal && newVal) || 
                            (oldVal && newVal && oldVal.name !== newVal.name)) {
                            // 集合改变时清空搜索结果
                            this.resetSearch();
                            // 同步selectedCollection和activeCollection
                            this.selectedCollection = newVal?.name;
                        }
                    },
                    deep: true,
                    immediate: true
                }
            },
            created() {
                // 加载集合列表
                this.fetchCollections();
            },
            methods: {
                // 获取集合列表
                fetchCollections() {
                    axios.get(`${API_BASE_URL}/collections`)
                        .then(response => {
                            this.collections = response.data.collections || [];
                            // 初始化选中当前活动的集合
                            if (this.activeCollection && this.activeCollection.name) {
                                this.selectedCollection = this.activeCollection.name;
                            }
                        })
                        .catch(error => {
                            console.error('获取集合列表失败:', error);
                            this.$message.error('获取集合列表失败: ' + (error.response?.data?.error || error.message));
                        });
                },
                
                // 执行向量搜索
                search() {
                    if (!this.searchQuery.trim()) {
                        this.$message({
                            message: '请输入搜索内容',
                            type: 'warning'
                        });
                        return;
                    }
                    
                    if (!this.isActiveCollectionValid) {
                        this.$message({
                            message: '请先选择一个集合',
                            type: 'warning'
                        });
                        return;
                    }
                    
                    this.loading = true;
                    const data = {
                        query: this.searchQuery,
                        limit: this.settings.limit,
                        minScore: this.settings.minScore
                    };
                    
                    axios.post(`${API_BASE_URL}/search`, data)
                        .then(response => {
                            this.searchResults = response.data.results || [];
                            
                            if (this.searchResults.length === 0) {
                                this.$message({
                                    message: '没有找到匹配的结果',
                                    type: 'info'
                                });
                            }
                        })
                        .catch(error => {
                            console.error('搜索失败:', error);
                            this.$message.error('搜索失败: ' + (error.response?.data?.error || error.message));
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                },
                
                // 查看文档详情
                viewDocument(document) {
                    this.$confirm('是否查看完整文档？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        // 创建包含文档内容的对话框
                        const h = this.$createElement;
                        this.$msgbox({
                            title: '文档详情',
                            message: h('div', null, [
                                h('p', null, [
                                    h('strong', null, 'ID: '),
                                    `${document.id}`
                                ]),
                                h('div', { class: 'document-content' }, document.content)
                            ]),
                            confirmButtonText: '关闭'
                        });
                    }).catch(() => {});
                },
                
                // 格式化文档内容（截断）
                formatContent(content) {
                    if (!content) return '';
                    return content.length > 150 ? content.substr(0, 147) + '...' : content;
                },
                
                // 打开设置对话框
                openSettings() {
                    this.settingsDialogVisible = true;
                },
                
                // 重置搜索
                resetSearch() {
                    this.searchQuery = '';
                    this.searchResults = [];
                },
                
                // 切换集合
                switchCollection(collectionName) {
                    const collection = this.collections.find(item => item.name === collectionName);
                    if (collection) {
                        this.loading = true;
                        // 通知后端切换集合
                        axios.post(`${API_BASE_URL}/collections/${collectionName}/use`)
                            .then(() => {
                                // 更新父窗口全局变量
                                window.parent.appGlobal.activeCollection = collection;
                                
                                // 强制更新组件，确保标题刷新
                                this.$forceUpdate();
                                
                                this.$message({
                                    message: `已切换到集合: ${collection.name}`,
                                    type: 'success'
                                });
                                // 切换集合后重置搜索结果
                                this.activeCollection.name=collection.name;
                                this.resetSearch();
                            })
                            .catch(error => {
                                console.error('切换集合失败:', error);
                                this.$message.error('切换集合失败: ' + (error.response?.data?.error || error.message));
                                // 回退选中的集合
                                this.selectedCollection = this.activeCollection?.name;
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }
                },
            }
        });
    </script>
</body>
</html>